package com.wwwarehouse.contract.create_warehouse_map;

import android.os.Bundle;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.fastjson.JSON;
import com.wwwarehouse.common.bean.response.CardDeskTaskResponseBean;
import com.wwwarehouse.common.bean.response.CommonClass;
import com.wwwarehouse.common.constant.Constant;
import com.wwwarehouse.common.custom_widget.ClearEditText;
import com.wwwarehouse.common.custom_widget.keyboard.VirtualKeyboardView;
import com.wwwarehouse.common.custom_widget.time_pick.BothSidesWithTextPickerDialog;
import com.wwwarehouse.common.eventbus_event.CardDeskEvent;
import com.wwwarehouse.common.fragment.PcImportUnifyFragment;
import com.wwwarehouse.common.tools.rsa.StringUtils;
import com.wwwarehouse.contract.bean.CreateMapBean;
import com.wwwarehouse.contract.bean.MaxFloorValueBean;
import com.wwwarehouse.contract.contract.TheParentFragment;
import com.wwwarehouse.contract.core.ContractConstant;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import contract.wwwarehouse.com.contract.R;
import de.greenrobot.event.EventBus;

/**
 * Created by feng.gao on 2017/10/17.
 * 创建仓库地图
 */
	@Route(path = "/contract/CreateWarehouseMapFragment")
public class CreateWarehouseMapFragment extends TheParentFragment implements View.OnClickListener {
	private VirtualKeyboardView mKeyBoard;
	private ClearEditText mConversionEdt;
	private TextView mFloorTv;
	private LinearLayout mFloorLayout;
	private Button mConfirmBtn;
	private CardDeskTaskResponseBean.TaskBean taskBean;
	private TextView mWarehouseNameTv;
	private List<String> floorList = new ArrayList<>();
	@Override
	protected int getContentId() {
		return R.layout.create_warehouse_map_fragment ;
	}

	@Override
	protected void init(View view) {
		for (int i = 1; i <  11 ; i++) {
			floorList.add(i + "");
		}

		/**
		 * 请求最大楼层数
		 */
		mConversionEdt = (ClearEditText) view.findViewById(R.id.conversion_edt);
		mWarehouseNameTv = (TextView) view.findViewById(R.id.warehouse_tv);
		mKeyBoard = (VirtualKeyboardView) view.findViewById(R.id.keyboard);
		mKeyBoard.isShowContentBar(false);
		mFloorTv = (TextView) view.findViewById(R.id.floor_tv);
		mConfirmBtn = (Button) view.findViewById(R.id.confirm_btn);
		mFloorLayout = (LinearLayout) view.findViewById(R.id.floor_layout);
		if (getArguments() != null && getArguments().getSerializable(Constant.KEY_CARD_DESK_TASK_DETAILS) != null){
			taskBean = (CardDeskTaskResponseBean.TaskBean) getArguments().getSerializable(Constant.KEY_CARD_DESK_TASK_DETAILS);
			if (taskBean != null) {
				if (StringUtils.isNoneNullString(taskBean.getCardExplain())) {
					mWarehouseNameTv.setText(StringUtils.getResourceStr(mActivity , R.string.warehouse_name_title , taskBean.getCardExplain()));
				}
			}

		}
		mFloorLayout.setOnClickListener(this);
		hideSystemKeyboard(mConversionEdt);
		mConfirmBtn.setOnClickListener(this);
		if (TextUtils.isEmpty(mConversionEdt.getText().toString())) {
			mConfirmBtn.setEnabled(false);
			mConfirmBtn.setBackground(mActivity.getResources().getDrawable(R.drawable.common_btn1_noclick_shape));
		} else {
			mConfirmBtn.setEnabled(true);
			mConfirmBtn.setBackground(mActivity.getResources().getDrawable(R.drawable.common_btn1_normal_shape));
		}
		mKeyBoard.setOnConfirmListener(new VirtualKeyboardView.OnConfirmListener() {
			@Override
			public void confirm() {
				if (mKeyBoard.getVisibility() == View.VISIBLE) {
					mKeyBoard.setVisibility(View.GONE);
				}
			}
		});
		mConversionEdt.setOnFocusChangeListener(new View.OnFocusChangeListener() {
			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				mKeyBoard.setEditText((EditText) v);
				if (mKeyBoard.getVisibility() != View.VISIBLE) {
					mKeyBoard.setVisibility(View.VISIBLE);
				}
			}
		});
		mConversionEdt.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				mKeyBoard.setFocusable(true);
				mKeyBoard.setFocusableInTouchMode(true);
				mKeyBoard.setEditText((EditText) v);
				if (mKeyBoard.getVisibility() != View.VISIBLE) {
					mKeyBoard.setVisibility(View.VISIBLE);
				}
			}
		});
		mConversionEdt.addTextChangedListener(new TextWatcher() {
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {

			}

			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				if (s.toString().contains(".")) {
					if (s.length() - 1 - s.toString().indexOf(".") > 2) {
						s = s.toString().subSequence(0,
								s.toString().indexOf(".") + 3);
						mConversionEdt.setText(s);
						mConversionEdt.setSelection(s.length());
					}
				}
				if (s.toString().trim().substring(0).equals(".")) {
					s = "0" + s;
					mConversionEdt.setText(s);
					mConversionEdt.setSelection(2);
				}

				if (s.toString().startsWith("0")
						&& s.toString().trim().length() > 1) {
					if (!s.toString().substring(1, 2).equals(".")) {
						mConversionEdt.setText(s.subSequence(0, 1));
						mConversionEdt.setSelection(1);
						return;
					}
				}
			}

			@Override
			public void afterTextChanged(Editable s) {
				judgeNumber(s);
				if (TextUtils.isEmpty(mConversionEdt.getText().toString())) {
					mConfirmBtn.setEnabled(false);
					mConfirmBtn.setBackground(mActivity.getResources().getDrawable(R.drawable.common_btn1_noclick_shape));
				} else {
					mConfirmBtn.setEnabled(true);
					mConfirmBtn.setBackground(mActivity.getResources().getDrawable(R.drawable.common_btn1_normal_shape));
				}
			}
		});
		silentHttpPost(ContractConstant.FLOOR_MAX_VALUE_METHOD , new HashMap() , 1 , true );

	}

	@Override
	public void setTitle() {
		if (peekFragment() instanceof CreateWarehouseMapFragment) {
			mActivity.setTitle(R.string.create_warehouse_map_title);
		}
	}

	@Override
	public void requestDatas() {

	}

	@Override
	public void onSuccess(CommonClass commonClass, int what) {
		if (what == 1) {
			//请求最大楼层数接口
			floorList.clear();
			MaxFloorValueBean maxFloorValueBean = JSON.parseObject(commonClass.getData().toString(), MaxFloorValueBean.class);
			if (maxFloorValueBean != null) {
				long maxValue = maxFloorValueBean.getMaxFloor();
				if (maxValue > 0) {
					//说明有最大楼层数
					for (int i = 1; i < maxValue + 1 ; i++) {
						floorList.add(i + "");
					}
				}

			}


		}else if (what == 2) {
			if (commonClass.getCode().equals("0")) {
				CreateMapBean bean = JSON.parseObject(commonClass.getData().toString(), CreateMapBean.class);
				if (bean != null) {
					EventBus.getDefault().post(new CardDeskEvent("clear_back_stack"));
					//跳转到手机转PC
					Bundle bundle = new Bundle();
					taskBean.setTaskType("IMPORT_STOCK_MAP");
					taskBean.setCardUkid(String.valueOf(bean.getOperationUkid()));
					bundle.putSerializable(Constant.KEY_CARD_DESK_TASK_DETAILS, taskBean);
					PcImportUnifyFragment pcImportUnifyFragment = new PcImportUnifyFragment();
					pcImportUnifyFragment.setArguments(bundle);
					pushFragment(pcImportUnifyFragment);
				}


			} else {
				toast(commonClass.getMsg());
			}


		}


	}

	@Override
	public void onReLoad(int code) {

	}

	private void hideSystemKeyboard(EditText... mNumber) {
		for (int i = 0; i < mNumber.length; i++) {
			// 设置不调用系统键盘
			if (android.os.Build.VERSION.SDK_INT <= 10) {
				mNumber[i].setInputType(InputType.TYPE_NULL);
			} else {
				mActivity.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

				Class<EditText> clazz = EditText.class;
				Method method;

				try {
					method = clazz.getMethod("setShowSoftInputOnFocus", boolean.class);
					method.setAccessible(true);
					method.invoke(mNumber[i], false);
				} catch (Exception e) {
					e.printStackTrace();
				}

				try {
					method = clazz.getMethod("setSoftInputShownOnFocus", boolean.class);
					method.setAccessible(true);
					method.invoke(mNumber[i], false);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}

	}

	@Override
	public void onClick(View v) {
		int clickId = v.getId();
		if (clickId == R.id.floor_layout) {
			if (mKeyBoard.getVisibility() == View.VISIBLE) {
				mKeyBoard.setVisibility(View.GONE);
			}
			String floor = mFloorTv.getText().toString();

			new BothSidesWithTextPickerDialog.Builder(mActivity).setData(floorList).setLeftTitle("共").setSelection(floor.substring(1 , floor.length() -1)).setTitle("选择楼层数").setRightTitle("层").setOnDataSelectedListener(new BothSidesWithTextPickerDialog.OnSelectedListener() {
				@Override
				public void onSelected(String s, int i) {
						mFloorTv.setText("共" + s + "层");
				}

				@Override
				public void onCancel() {

				}
			}).create().show();
		} else if (clickId == R.id.confirm_btn) {
			//请求接口
			if (taskBean != null) {
				Map<String, Object> map = new HashMap<>();
				map.put("businessUnitId", taskBean.getBelongBusiness());
				map.put("operationUkid", taskBean.getCardUkid());
				map.put("userId", sp.getValue(Constant.sp_User_Id));
				Map<String, Object> warehouseMap = new HashMap<>();
				warehouseMap.put("name", taskBean.getCardExplain());
				warehouseMap.put("num", mFloorTv.getText().toString().substring(1, mFloorTv.getText().toString().length() - 1));
				warehouseMap.put("scale", mConversionEdt.getText().toString().trim());
				map.put("warehouse", warehouseMap);
				httpPost(ContractConstant.IMPORT_MAP_SAVE_WAREHOUSE_METHOD , map , 2 , true , "正在保存...");

			}

		}
	}

	/**
	 * 金额输入框中的内容限制（最大：小数点前五位，小数点后2位）
	 * @param edt
	 */
	public void judgeNumber(Editable edt){

		String temp = edt.toString();
		int posDot = temp.indexOf(".");//返回指定字符在此字符串中第一次出现处的索引
		if (posDot <= 0) {//不包含小数点
			if (temp.length() <= 5) {
				return;//小于五位数直接返回
			} else {
				edt.delete(5, 6);//大于五位数就删掉第六位（只会保留五位）
				return;
			}
		}
		if (temp.length() - posDot - 1 > 2)//如果包含小数点
		{
			edt.delete(posDot + 3, posDot + 4);//删除小数点后的第三位
		}
	}
}
